import { PrismaClient } from "@prisma/client";

const prismaClientSingleton = () => {
    const client = new PrismaClient();
    try {
        console.log("db start connect...");
        client.$connect();
        console.log("db connect success!!!");
    } catch (error) {
        console.log("db connect failed");
        client?.$disconnect();
    }
    return client;
};

type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>;

const globalForPrisma = globalThis as unknown as {
    prisma: PrismaClientSingleton | undefined;
};

const prisma = globalForPrisma.prisma ?? prismaClientSingleton();

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;

export default prisma;